package com.gx.auth.controller;

import com.gx.auth.common.AjaxResult;
import com.gx.auth.common.tree.Node;
import com.gx.auth.entity.Function;
import com.gx.auth.service.FunctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;

/**
 * Created by Administrator on 2017/4/4.
 */
@Controller
@RequestMapping("/function")
public class FunctionController {
    @Autowired
    private FunctionService functionService;
    @Autowired
    private NativeCache nativeCache;

    @RequestMapping("/index")
    public String menuList(){
        return "recurity/function/function_list";
    }

    @PostMapping("addEditFunction")
    @ResponseBody
    public AjaxResult addEditFunction (Function function){
        if (function.getId() == null){
            function.setSerialNum(nativeCache.getFunction().size());
            functionService.addFunction(function);
            nativeCache.addFunction(function);
        }else {
            functionService.updateUrl(function.getId(),function.getUrl());
            nativeCache.replaceFunction(function);
        }
        return AjaxResult.success();
    }

    @PostMapping("/deleteFunction")
    @ResponseBody
    public  AjaxResult deleteFunction (Long id){
        functionService.deleteFunctionById(id);
        nativeCache.removeFunction(id);
        return AjaxResult.success();
    }

    @PostMapping("/getSubFunctions")
    @ResponseBody
    public List<Function> getSubFunctions (Integer page ,Integer rows,Long parentId){
        if (Objects.equals(null,parentId)){
            parentId = 0L;
        }
        return functionService.getFunctions(page,rows,parentId);
    }

    @PostMapping("/buildFunctionTreeForEdit")
    @ResponseBody
    public List<Node> buildFunctionTreeForEdit (){
        if (Objects.equals(null,parentId)){
            parentId = 0L;
        }
        return functionService.getFunctions(page,rows,parentId);
    }



}
